package com.tomkk;

import com.google.gson.Gson;
import com.tomkk.utils.Error;
import com.tomkk.utils.MysqlOperation;
import com.tomkk.utils.Success;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by Tomkk on 2016/6/5.
 */
@WebServlet(name = "deleteUserHistory", urlPatterns = "/deleteUser")
public class deleteUserHistory extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        int user_id = Integer.parseInt(req.getParameter("user_id"));

        MysqlOperation operation = new MysqlOperation();
        Connection connection = operation.checkConn();
        Gson gson = new Gson();
        String json = null;
        try {
            connection.setAutoCommit(false);
            String sql = "DELETE FROM user WHERE user_id = "+user_id+";";
            operation.update(sql);
            sql = "DELETE FROM achievement WHERE user_id = "+user_id+";";
            operation.update(sql);
            sql = "DELETE FROM news_comment WHERE user_id = "+user_id+";";
            operation.update(sql);
            sql = "DELETE FROM achievement_comment WHERE user_id = "+user_id+";";
            operation.update(sql);
            connection.commit();
            json = gson.toJson(new Success(0,"删除成功"));
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            json = gson.toJson(new Error(2,"删除失败"));
        }
        PrintWriter writer = resp.getWriter();
        writer.print(json);
        writer.flush();
    }
}
